package com.eslserver.action.dropdown;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.eslserver.core.aware.GroupAware;
import com.eslserver.dao.DAOException;
import com.eslserver.dao.ESLDAO;
import com.eslserver.dao.ESLServerDAOFactory;
import com.eslserver.to.ESL;
import com.eslserver.util.JSONResponseUtil;

@SuppressWarnings("serial")
public class GroupESLDropdownServlet extends HttpServlet implements GroupAware {

	public static final Logger LOG = LoggerFactory
			.getLogger(GroupESLDropdownServlet.class);

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		PrintWriter writer = resp.getWriter();
		try {
			ESLDAO eslDAO = ESLServerDAOFactory.getDAOFactory(
					ESLServerDAOFactory.ESLSERVER_DAOFACTORY).getESLDAO();

			Map<Integer, String> selectedEslMap = new HashMap<Integer, String>();
			Map<Integer, String> availableESLMap = new HashMap<Integer, String>();
			ArrayList<Map<Integer, String>> ESLCollection = new ArrayList<Map<Integer, String>>();

			if (req.getParameter(PARAM_GROUP_ID) != null
					&& Integer.parseInt(req.getParameter(PARAM_GROUP_ID)) > 0) {
				System.out.println("test");
				for (ESL esl : eslDAO.loadAllESLs()) {
					if (esl.getGroup() == null) {
						availableESLMap.put(esl.getESLID(), esl.getName());
					} else if (esl.getGroup().getGroupID() == Integer
							.parseInt(req.getParameter(PARAM_GROUP_ID))) {
						selectedEslMap.put(esl.getESLID(), esl.getName());
					}
				}
			} else {
				for (ESL esl : eslDAO.loadAllESLs()) {
					if (esl.getGroup() == null)
						availableESLMap.put(esl.getESLID(), esl.getName());
				}
			}
			ESLCollection.add(selectedEslMap);
			ESLCollection.add(availableESLMap);

			writer.println(JSONResponseUtil.getJSONObjectString(ESLCollection));

		} catch (DAOException e) {
			LOG.error("error laoding ESLs", e);
		}
	}
}
